//
//  HEIMGroupDetailsViewController.m
//  HealthElderly
//
//  Created by 吴欧 on 2021/11/22.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HEIMGroupDetailsViewController.h"
#import "UICollectionView+LTCollectionViewLayoutCell.h"
#import "ZLCollectionViewVerticalLayout.h"
#import "HEIMGroupMemberItem.h"
#import "HEIMGroupMemberModel.h"
#import "HEIMGroupDetailsTitleCell.h"
#import "HEIMGroupSectionTitleView.h"
#import "HEIMNotificationViewController.h"
#import "HEDoctorMainPageViewController.h"

@interface HEIMGroupDetailsViewController ()<UICollectionViewDataSource,UICollectionViewDelegate, ZLCollectionViewBaseFlowLayoutDelegate, LTCollectionViewDynamicHeightCellLayoutDelegate>

@property (nonatomic, strong) NSMutableArray <NSMutableArray *> *dataSource;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *titles;

@property (nonatomic, assign) CGFloat cellMargin;

@end

@implementation HEIMGroupDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"群聊信息";
    self.view.backgroundColor = CViewBgColor;

    [self initUI];
    [self loadTeamUsersData];
}

- (void)initUI {
    _cellMargin = 20;
    _titles = @[@"工作人员", @"服务对象", @" "];
    _dataSource = @[].mutableCopy;
    
    [self.view addSubview:self.collectionView];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(ZXNavBarHeight);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
}

- (void)loadTeamUsersData {

    __weak typeof(self) weakself = self;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:_session.sessionId forKey:@"groupId"];
     
    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KqueryGroupMembers parameters:dict success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        NSArray * users = [HEIMGroupMemberModel mj_objectArrayWithKeyValuesArray:response.data];
        
        self.title = [NSString stringWithFormat:@"%@（%ld）", @"群聊信息", users.count];

        NSMutableArray *workers = @[].mutableCopy;
        NSMutableArray *publics = @[].mutableCopy;
        HEIMKitInfo *master = nil;
        
        for (HEIMGroupMemberModel *user in users) {
            HEIMKitInfo *doc = [HEIMKitInfo new];
            doc.infoId = user.id;
            doc.showName = user.name;
            doc.avatarUrlString = user.portrait;
            doc.memberType = user.memberType;
            doc.avatarImage = user.memberType == HEIMGroupMemberTypeGroupMaster || user.memberType == HEIMGroupMemberGroupWorker ? IMAGE_NAMED(@"hmang") : IMAGE_NAMED(@"defualt_icon");
            
            // 1 群主
            if (doc.memberType == HEIMGroupMemberTypeGroupMaster) {
                master = doc;
            }
            else if (doc.memberType == HEIMGroupMemberGroupOrdinary) {
                [publics addObject:doc];
            }else if (doc.memberType == HEIMGroupMemberGroupWorker) {
                [workers addObject:doc];
            }
        }
        
        [workers insertObject:master atIndex:0];
        
        [self.dataSource addObject: workers];
        [self.dataSource addObject: publics];
        [self.dataSource addObject: @[@{@"id":@1, @"title": @"通知公告"}]];

        [self.collectionView reloadData];

    } failure:^(NSError * _Nonnull error) {
    }];
}

#pragma mark - lary
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        // 1.创建流水布局
        ZLCollectionViewVerticalLayout *flowLayout = [[ZLCollectionViewVerticalLayout alloc] init];
        flowLayout.delegate = self;

        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = CViewBgColor;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.alwaysBounceVertical = YES;
 
        [_collectionView registerClass:[HEIMGroupMemberItem class] forCellWithReuseIdentifier:@"HEIMGroupMemberItem"];
        [_collectionView registerClass:[HEIMGroupDetailsTitleCell class] forCellWithReuseIdentifier:@"HEIMGroupDetailsTitleCell"];
        [_collectionView registerClass:[HEIMGroupSectionTitleView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier: KHEIMGroupSectionTitleView];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier: @"UICollectionReusableView"];

    }
    return _collectionView;
}

#pragma mark - ZLCollectionViewBaseFlowLayoutDelegate
//指定section用的样式。LabelLayout是标签样式，ClosedLayout用于tableviewcell或者瀑布流，九宫格之类的。
- (ZLLayoutType)collectionView:(UICollectionView *)collectionView layout:(ZLCollectionViewBaseFlowLayout *)collectionViewLayout typeOfLayout:(NSInteger)section {
    return ClosedLayout;
}

//如果是ClosedLayout样式的section，必须实现该代理，指定列数
- (NSInteger)collectionView:(UICollectionView *)collectionView layout:(ZLCollectionViewBaseFlowLayout *)collectionViewLayout columnCountOfSection:(NSInteger)section {
    NSInteger colum = 1;
    if (section <= 1) {
        colum = 5;
    }
    return colum;
}

- (UIColor*)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewFlowLayout *)collectionViewLayout backColorForSection:(NSInteger)section {
    return KWhiteColor;
}

#pragma mark UICollectionViewDataSource
#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _dataSource.count;
}

// 每个分区上得元素个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataSource[section].count;
}

// 设置cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MCCollectionBaseCell *cell;
    if (indexPath.section <= 1) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier: @"HEIMGroupMemberItem" forIndexPath:indexPath];
    }else {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier: @"HEIMGroupDetailsTitleCell" forIndexPath:indexPath];
    }
    [cell configCellWithModel:_dataSource[indexPath.section][indexPath.row] indexPath:indexPath];
    return cell;
}

// 设置cell大小 itemSize：可以给每一个cell指定不同的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    KWeakSelf
    if (indexPath.section <= 1) {
        CGFloat cellHeight = [collectionView lt_heightForCellWithIdentifier:@"HEIMGroupMemberItem" fixedWidth:KScreenWidth cacheByIndexPath:indexPath configuration:^(MCCollectionBaseCell *cell) {
            [cell configCellWithModel:weakSelf.dataSource[indexPath.section][indexPath.row] indexPath:indexPath];
        }];
        return CGSizeMake(KScreenWidth, cellHeight);
    }else {
        CGFloat cellHeight = [collectionView lt_heightForCellWithIdentifier:@"HEIMGroupDetailsTitleCell" fixedWidth:KScreenWidth cacheByIndexPath:indexPath configuration:^(MCCollectionBaseCell *cell) {
            [cell configCellWithModel:weakSelf.dataSource[indexPath.section][indexPath.row] indexPath:indexPath];
        }];
        return CGSizeMake(KScreenWidth, cellHeight);
    }
    return CGSizeMake(0, 0);
}


// 设置UIcollectionView整体的内边距（这样item不贴边显示）
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    // 上 左 下 右
    if (section <= 1) {
        return UIEdgeInsetsMake(0, _cellMargin , 0, _cellMargin);
    }
    return UIEdgeInsetsMake(0, 0 , 0, 0);
}

// 设置minimumLineSpacing：cell上下之间最小的距离
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return _cellMargin;
}

// 设置minimumInteritemSpacing：cell左右之间最小的距离
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return _cellMargin;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section <= 1) {
        return CGSizeMake(kScreenWidth, 50);
    }
    return CGSizeMake(kScreenWidth, 10);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if([kind isEqualToString:UICollectionElementKindSectionHeader] && indexPath.section <= 1){
        HEIMGroupSectionTitleView *supplementaryView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier: KHEIMGroupSectionTitleView forIndexPath:indexPath];
        [supplementaryView refreshTitle:_titles[indexPath.section]];
        return supplementaryView;
    }
    
    UICollectionReusableView *supplementaryView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier: @"UICollectionReusableView" forIndexPath:indexPath];
    return supplementaryView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        HEIMKitInfo * doc = self.dataSource[indexPath.section][indexPath.item];
        HEDoctorMainPageViewController *vc = [HEDoctorMainPageViewController new];
        vc.userId = doc.infoId;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.section == 2) {
        if (indexPath.item == 0) {
            HEIMNotificationViewController *vc = [HEIMNotificationViewController new];
            vc.session = self.session;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}


@end
